package com.hxhy.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.hxhy.bean.Account;
import com.hxhy.bean.BElectronic;
import com.hxhy.bean.Taxrate;
import com.hxhy.dao.InvoiceMapper;
import com.hxhy.log.Logger;
import com.hxhy.util.Tools;

public abstract class InvoiceServiceImpl implements InvoiceService {

	@Autowired
	protected InvoiceMapper mapper;

	protected Logger log = Logger.getLogger();
	/**
	 * @税率集合
	 * @年度_面积类型名称 @税收表示(0免税,1含税)
	 */
	protected static Map<String, Taxrate> tax;

	@Override
	public void init() {
		try {
			List<Taxrate> list = mapper.taxrate();
			for (Taxrate tx : list) {
				if (tax == null)
					tax = new HashMap<String, Taxrate>();
				tx.setIsdutyfree("是".equals(tx.getIsdutyfree()) ? "0" : "1");
				tax.put(tx.getAreakind(), tx);
			}
		} catch (Exception e) {
			log.info(Tools.getErrorException(e));
		}
	}

	/**
	 * @账目是否免税
	 * @param ac
	 * @return
	 */
	protected boolean isdutyfree(Account ac) {
		if (ac != null && tax.containsKey(ac.getAreakind())) {
			return "0".equals(tax.get(ac.getAreakind()).getIsdutyfree());
		}
		return true;
	}

	/**
	 * @账目税率
	 * @param ac
	 * @return
	 */
	protected BigDecimal taxrate(Account ac) {
		if (ac != null && tax.containsKey(ac.getAreakind())) {
			return tax.get(ac.getAreakind()).getTaxrate();
		}
		return BigDecimal.ZERO;
	}

	/**
	 * @失败信息填充
	 */
	protected BElectronic error(BElectronic be, String msg) {
		if (be == null)
			be = new BElectronic();
		be.setReturncode("9999");
		be.setReturnstate(msg);
		return be;
	}

	/**
	 * @验证账目是否开票
	 */
	protected boolean iskp(String taskid) {
		return iskp(taskid, null);
	}

	/**
	 * @验证账目是否开票
	 */
	protected boolean iskp(String taskid, String houseid) {

		StringBuilder sql = new StringBuilder();
		sql.append("SELECT count(1) hs from b_invoice_electronic i INNER JOIN b_accountdetail a ");
		sql.append("ON FIND_IN_SET(a.id,CONCAT('-1',',',i.accountids))>0 WHERE a.taskid='");
		sql.append(taskid).append("' AND i.returncode IN('0000','1001') AND i.flag='0' ");
		if (!Tools.isNullOrEmpty(houseid))
			sql.append("AND a.houseid='").append(houseid).append("' ");

		return 0 < mapper.execSelectInt(sql.toString()).intValue();
	}

	/**
	 * @拼接账目id
	 */
	protected String accountids(String taskid) {
		return mapper.accountids(taskid, null);
	}

}
